package com.mulder.study.netty;

import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.Bootstrap;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;


/**
 * very very simple netty client bootStrap
 * @author Administrator
 *
 */
public class MulderNettyBootStrap 
{
	private static Logger logger = Logger.getLogger(MulderNettyBootStrap.class);
	
	private ChannelFactory factory;
	private Bootstrap bootstrap;
	
	private boolean isServer = false;
	
	public MulderNettyBootStrap(boolean isServer)
	{
	    super();
	    this.isServer = isServer;
	    initFactory();
	}
	
	private void initFactory() 
	{
	    if(isServer) 
	    {
	        factory = new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool());
                bootstrap = new ServerBootstrap(factory);
	    }
	    else
	    {
	        factory = new NioClientSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool());
	        bootstrap = new ClientBootstrap(factory);
	    }
		
	    bootstrap.setOption("tcpNoDelay", true);
	    bootstrap.setOption("keepAlive", true);
		
	    logger.info( "MulderNettyBootStrap "+(isServer?"ServerMode" : "ClientMode")+" Load !");
	}
	
	public Bootstrap getBootStrap() 
	{
	    return this.bootstrap;
	}
	
	public void releaseExternalResources() 
	{
	    this.bootstrap.releaseExternalResources();
	    this.factory.releaseExternalResources();
	    this.bootstrap = null;
	    this.factory = null;
		
	    logger.info( "MulderNettyBootStrap Closed");
	}
}